<?php
// 应用公共文件
/**
 * 模型内统一数据返回
 * @param $code
 * @param string $msg
 * @param array $data
 * @return array
 */

if (!function_exists('dataReturn')) {

    function dataReturn($code, $msg = 'success', $data = [])
    {
        return ['code' => $code, 'data' => $data, 'msg' => $msg];
    }
}

/**
 * 统一返回json数据
 * @param $code
 * @param string $msg
 * @param array $data
 * @return \think\response\Json
 */
if (!function_exists('jsonReturn')) {

    function jsonReturn($code, $msg = 'success', $data = [])
    {
        return json(['code' => $code, 'data' => $data, 'msg' => $msg]);
    }
}

/**
 * 统一分页返回
 * @param $list
 * @return array
 */
if (!function_exists('pageReturn')) {

    function pageReturn($list)
    {
        if (0 == $list['code']) {
            return ['code' => 0, 'msg' => 'success', 'data' => [
                'total' => $list['data']->total(),
                'rows' => $list['data']->all()
            ]];
        }

        return ['code' => 0, 'msg' => 'success', [
            'total' => 0,
            'rows' => []
        ]];
    }
}

/**
 * 生成密码
 * @param $password
 * @param $salt
 * @return string
 */
function makePassword($password, $salt = '')
{

    if (empty($salt)) {
        $salt = config('shop.salt');
    }

    return sha1(md5(md5($password . $salt)));
}

/**
 * 生成子孙树
 * @param $data
 * @return array
 */
function makeTree($data)
{

    $res = [];
    $tree = [];

    // 整理数组
    foreach ($data as $key => $vo) {
        $res[$vo['id']] = $vo;
    }
    unset($data);

    // 查询子孙
    foreach ($res as $key => $vo) {
        if ($vo['pid'] != 0) {
            $res[$vo['pid']]['children'][] = &$res[$key];
        }
    }

    // 去除杂质
    foreach ($res as $key => $vo) {
        if ($vo['pid'] == 0) {
            $tree[] = $vo;
        }
    }
    unset($res);

    return $tree;
}

/**
 * 构建树形结构（通用方法）
 * @param array $list
 * @param int $pid
 * @param string $idKey
 * @param string $pidKey
 * @return array
 */
if (!function_exists('buildTree')) {
    function buildTree(array $list, int $pid = 0, string $idKey = 'id', string $pidKey = 'pid'): array
    {
        $tree = [];
        foreach ($list as $item) {
            if ($item[$pidKey] == $pid) {
                $children = buildTree($list, $item[$idKey], $idKey, $pidKey);
                if (!empty($children)) {
                    $item['children'] = $children;
                }
                $tree[] = $item;
            }
        }
        return $tree;
    }
}

function now()
{
    return date('Y-m-d H:i:s');
}

/**
 * 跨域配置
 */
function crossDomain()
{
    header("access-control-allow-headers: X-CSRF-TOKEN, Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-Requested-With");
    header("access-control-allow-methods: OPTIONS, GET, POST, PATCH, PUT, DELETE");
    header("access-control-allow-origin: *");
}

/**
 * 获取当前用户
 * @param $config
 * @return array|null
 */
function getUserInfo($config = '')
{
    return getJWT(getHeaderToken(), $config);
}

/**
 * 从头部获取token
 * @return bool|string
 */
function getHeaderToken()
{
    $header = request()->header();
    if (isset($header['authorization'])) {
        return substr($header['authorization'], 7);
    }

    return '';
}

/**
 * 设置jwt
 * @param $data
 * @param $config
 * @return string
 */
function setJWT($data, $config = '')
{
    if (empty($config)) {
        $config = \config('erp.jwt_key');
    }

    $jwt = new Firebase\JWT\JWT();
    $token = [
        // "iss"  => "http://example.org", // 签发者
        // "aud"  => "http://example.com", // 认证者
        'iat' => time(), // 签发时间
        'nbf' => time(), // 生效时间
        'exp' => (time() + 60 * 60 * 24 * 7), // 过期时间  7天后的时间戳
        'data' => $data
    ];

    return $jwt::encode($token, $config, 'HS256');
}

/**
 * 获取token中的信息
 * @param $token
 * @param $config
 * @return array|null
 */
function getJWT($token, $config = '')
{
    if (empty($config)) {
        $config = \config('erp.jwt_key');
    }

    if (empty($token)) {
        return [];
    }

    $jwt = new Firebase\JWT\JWT();

    try {
        $jwtData = $jwt::decode($token, new Firebase\JWT\Key($config, 'HS256'));
        $data = (array)($jwtData->data);
    } catch (\Exception $e) {
        return null;
    }
    return $data;
}